var express = require('express');
var router = express.Router();
const request = require('request');

router.get('/', async function(req, res, next) {
	const query = req.query;
	const {
		url,
		downtype = 'video'
	} = query;
	const file_url = getUrl(url);
	const _data = await request(encodeURI(file_url), 'stream');
	res.attachment(`${+new Date()}.${downtype=='video'?'mp4':'jpeg'}`);
	_data.pipe(res);
});
module.exports = router;

function getUrl(s) {
	const reg = /(https?|http|ftp|file):\/\/[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]/g;
	s = s.match(reg);
	return (s && s.length ? s[0] : null);
}
